/**
 * Copyright (c) 2012 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.wordraster.rastersolver;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class InMemoryTreeDB implements iStringDatabase {
  private final Map<String, Language> myLoadedWords = new HashMap<String, Language>();

  @Override
  public boolean isLanguageLoaded(String aLanguage) {
    return myLoadedWords.containsKey(aLanguage);
  }

  @Override
  public boolean isValidWord(String aLanguage, String aWord) {
    return myLoadedWords.get(aLanguage).getTrie().containKey( aWord );
  }
  
  @Override
  public boolean isValidPrefix( String aLanguage, String aPrefix ) {
    return myLoadedWords.get(aLanguage).getTrie().containPrefix( aPrefix );
  }


  @Override
  public RandomLetterHelper getRandomLetterHelper(String aLanguage) {
    return myLoadedWords.get(aLanguage).getRandomLetterHelper();
  }

  @Override
  public void beginInsertingWords( String aLanguage ) {
    myLoadedWords.put( aLanguage, new Language( new RandomLetterHelper(), new TrieNode() ) );
  }

  @Override
  public void endInsertingWords( String aLanguage ) {
    myLoadedWords.get(aLanguage).getRandomLetterHelper().calculateTotalLetterOccurance();
    
  }

  @Override
  public void insertWord( String aLanguage, String aWord ) throws IOException {
    myLoadedWords.get(aLanguage).addWord( aWord );
  }
  
  private class Language{
    private final RandomLetterHelper myRandomLetterHelper;
    private final TrieNode myTrieNode;

    public Language(RandomLetterHelper aRandomLetterHelper,
        TrieNode aTrieNode) {
      myRandomLetterHelper = aRandomLetterHelper;
      myTrieNode = aTrieNode;
    }

    public RandomLetterHelper getRandomLetterHelper() {
      return myRandomLetterHelper;
    }

    public TrieNode getTrie() {
      return myTrieNode;
    }
    
    public void addWord(String aWord){
      myRandomLetterHelper.addWord( aWord );
      myTrieNode.insert( aWord );
    }
  }

  @Override
  public void insertingWordsCompleted( String aLanguage ) {
    // TODO Auto-generated method stub
    
  }

  @Override
  public void close() {
  }

}
